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??

whitebear
  • 11,200
  • 24
  • 114
  • 237

2 Answers2

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.

ram
  • 78
  • 1
  • 8
  • Thank you very much for your comment. Also I need to understand the const/let – whitebear May 18 '20 at 01:32
  • https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var has a very good details – ram May 18 '20 at 01:38
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)
hoangdv
  • 15,138
  • 4
  • 27
  • 48