1

I have this script.

var myDiv = `<span class=name">mytext<span>`;

//change font size for $(myDiv)
$(myDiv).find('span.name').css('font-size','3px');

// but myDiv is not changed....
var html = `<div>{$myDiv}</div>`;

maybe I need the way to return the change of $(myDiv) to myDiv

is there any good way??

3
  • Create a myDiv jquery object, make change and then use innerHTML to stringify it. Commented May 14, 2020 at 3:10
  • Also find() won't work when the element you want is at root level of the html string. Use filter() for root elements Commented May 14, 2020 at 3:11
  • Please review this link api.jquery.com/html Commented May 14, 2020 at 3:19

2 Answers 2

1

You are so close!

Your html string is not valid (require close tag, " for class name).

The .find('span.name') function return "nothing", because span now is root and the root element just has a text node (mytext).

Just wrap you span into a div object, then do as you do to access to your span element. In this case you append style attribute for the element.

const myDiv = `<span class="name">mytext</span>`; // I corrected you html string

const $ele = $('<div>').append(myDiv); // wrap your html string into a div element, now div is root

$ele.find('span.name').css('font-size', '3px'); // append style attr

const html = `<div>${$ele.html()}</div>`; // html() mean inside html string (inside div)
Sign up to request clarification or add additional context in comments.

Comments

1

Posting this as a answer as I don't have enough points to comment. In your code - you have NOT quoted the class properly - class=name" This needs to be fixed.

Other than that - as of now, myDiv is a string - it is not getting added to the DOM - that code seems to be missing in your question above.

Once you add the string in myDiv to DOM - you will be able to do other changes For example:

const $div = $(myDiv).appendTo('body');
$div.css('font-size','3px');

I'm hoping you will be able to use const/let instead of var.

2 Comments

Thank you very much for your comment. Also I need to understand the const/let

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.