Ryan - Llaver
Ryan - Llaver

Reputation: 526

Set style of element being added with .before() when a variable is needed

I am creating an element using the jQuery function .before() as so:

d.children().first().before("<div class='test-div'><span class='test-span'>" + text + "</span></div>")

I'm trying to set the style of the span which is all fine by just adding a style='left:10px' attribute right after the class, however I need the pixel count to be a variable so it would look something like this:

"...style='"left" + leftOffset'..."

However, since the .before() function requires the use of the double quotes (" ") this is not working. I tried using .style() after .before() but i get:

Uncaught TypeError: d.children(...).first(...).before(...).style is not a function

Is there a solution to this that I'm missing or will I need to apply the style in some other way?

Others thought this was a duplicate question, but the linked question is quite inherently different. I didn't need to escape a single quote. Basically I needed to use a third set of quotes inside two sets.

Upvotes: 0

Views: 44

Answers (1)

SourceOverflow
SourceOverflow

Reputation: 2048

I don't fully understand where the problem lies.

d.children().first().before("<div class='test-div'><span class='test-span' style='" + (left + leftOffset) + "'>" + text + "</span></div>")

should work just fine.

Upvotes: 1

Related Questions