0

I have a variable with some html

var myvar = '<div id="myid">something here</div>';

How can I add some css inline to that variable like:

$(myvar).css("border","1px solid red"); 

If this possible?

1
  • What you will do with that result? Commented Mar 18, 2016 at 9:42

2 Answers 2

3

Your code is working fine

var myvar = '<div id="myid">something here</div>';

myvar = $(myvar).css({
  "border":"1px solid red",
  "color": "blue"
}); 

$(myvar).appendTo("body");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

but if you want to apply css using your id selector you need to append the myvar to DOM FIRST

var myvar = '<div id="myid">something here</div>';
$(myvar).appendTo("body");
myvar = $("#myid").css({
  "border":"1px solid red",
  "color": "blue"
}); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

2

After applying css get outerHTML property of dom object. Use of filter() and find() depends your markup.

var myvar = '<div id="myid">something here</div>';
myvar = $(myvar)
  //get element with id
  .filter('#myid')
  // apply css ,                   
  .css("border", "1px solid red")
  // go back to previous selector and get dom object  
  .end()[0]
  // get outerHTML property of dom object
  .outerHTML;

console.log(myvar);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


or generate a temporary div and apply string as html property and then find the id inside, after get markup of temporary div

var myvar = '<div id="myid">something here</div>';
// generate div with html content as string
myvar = $('<div/>', {
    html: myvar
  })
  // get id element from it
  .find('#myid')
  // apply css
  .css("border", "1px solid red")
  // go back to previous selector
  .end()
  // get html content of temporary div
  .html();

console.log(myvar);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

1 Comment

I need to add the inline style to the id myid as there's other div's in the string that I might want to target

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.