0

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" >&#xE834;</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" >&#xE5CA;</i>');

but at the end it returns only

< i class="material-icons" >&#xE834;</i>

without the surrounding the dive.

asked Sep 8, 2017 at 16:25
1
  • I don't think you understand how jQuery html works. the variables s, x, a, and t are all the same element. Commented Sep 8, 2017 at 16:30

2 Answers 2

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 : '&#xE834;'
});
$('div').empty().append(button, i); // add elements to DOM
i.addClass('.mdl-color-text--green-600'); // add another class to an element
answered Sep 8, 2017 at 16:30

Comments

0

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 = "&#xE834;";
 // 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('&#xE834;');
// append elements
button.append(icon);
baseElement.append(button);
answered Sep 8, 2017 at 18:01

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.