user3352464 user3352464 - 1 year ago 132
CSS Question

How do I style an element dynamically created by javascript

I am new to front-end development. I was trying to code an annotation tool. A sample screen is shown on the image below. After the user select a sentence, an annotation box is added on the right side bar at the same horizontal position as the highlighted sentence.

I want to edit the styles of the newly created html element, but how can I do that?

enter image description here

Here is my html structure:

<section id="main">
<div class="row">
<div class="small-8 large-8 columns"id="rawdata">

<p> <span class="sentence">2:22 So, last time I was here, I don't know if I told you this, but, um, we kind of did a "I like, I wish" activity on paper, about things that you like about studio, and things that you wish would change.</span><span class="sentence"> Um, do you want to share any of those thoughts now, so maybe we can talk about them? [name], I have yours if you want to look at it again.</span></p>
<p><span class="sentence">2:47 I forgot to add something.</span></p>
<p><span class="sentence">2:54 Well, I don't know, in terms of what I dislike about studio.</span></p>
<p><span class="sentence">2:57 So, some people wrote in theirs that, um, they dislike how cluttered it gets.</span></p>

<p><span class="sentence">5:09 I don't get bothered.</span>< <span class="sentence">I like the draftiness, I'm a little...</span><span class="sentence"> I'm one of the ones that opens the windows, and like—</span></p>
</div>
<div class="small-4 large-4 columns" id="annotations"><p></p>
</div>
</div>
</section>


JS for selecting sentence and adding annotations:

<script>
$('.sentence').click(function() {
$(this).toggleClass('sentenceStyle');
var y = $(this).offset().top;
y = parseInt(y) + 'px';

var para = document.createElement("p");
$("#annotations").append(para);
para.innerHTML="this is an annotation";
para.css('color','yellow');
});
</script>


And here it is the fiddle: http://jsfiddle.net/yujuns/HDe6v/3/

Answer Source

You are getting mixed up a bit switching between jQuery and native script.

css() is a jQuery method, but para is a DOM element.

Learn to use browser console/ developer tools to look for errors. You should see one for para.css().

I would suggest either using all natve script methods or using all jQuery methods for DOM manipulation and try not to mix them.

Using jQuery you can create the same p using:

var para = $('<p>').text("this is an annotation").css('color','yellow');

Using the code you have to change the style you need to create a jQuery object from para to be able to use css()

$(para).css('color','yellow');

Alternatively you could use native properties to change the style directly on the DOM element itself also

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download