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.

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
Sign up to request clarification or add additional context in comments.

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);

Comments

Your Answer

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.