I have a jquery elemnt s and i need to insert inside another elemnt
var s = $('div').html('<button class="mdl-button"></button>');
var x = s.html('< i class="material-icons" ></i>');
var a=x.addClass('.mdl-color-text--green-600');
then apply the css class to the inner html
var t=s.html('<i class="material-icons" ></i>');
but at the end it returns only
< i class="material-icons" ></i>
without the surrounding the dive.
-
I don't think you understand how jQuery html works. the variables s, x, a, and t are all the same element.Namaskar– Namaskar2017年09月08日 16:30:52 +00:00Commented Sep 8, 2017 at 16:30
2 Answers 2
Create the elements with jQuery instead, so you have references to them
var button = $('<button />', { // create a "button"
'class' : 'mdl-button'
}),
i = $('<i />', { // create a "i"
'class' : 'material-icons',
html : ''
});
$('div').empty().append(button, i); // add elements to DOM
i.addClass('.mdl-color-text--green-600'); // add another class to an element
Comments
Conceptually I think it might be helpful for you to see this in plain JavaScript. jQuery is doing this stuff in the background of the html command.
// First Get your Selector
let s = document.querySelector('div');
// Create your element and add any necessary details
let b = document.createElement('button');
b.className = 'mdl-button';
// create your icon and add details
let i = document.createElement('i');
i.className = 'material-icons mdl-color-text--green-600';
i.innerText = "";
// add icon to button, and button to div element
b.appendChild(i);
s.appendChild(b);
In your attempt you are doing several things to the same element which causes them to overwrite. Instead you would want to create the elements and then append them.
// get your root element, build button and icon
let baseElement = $('div')
, button = $('<button>').addClass('mdl-button')
, icon = $('<i>').addClass('material-icons mdl-color-text--green-600').text('');
// append elements
button.append(icon);
baseElement.append(button);