poor boy
poor boy

Reputation: 23

How to insert a text-like element into document using javascript and CSS?

I want to use javascript to insert some elements into the current page. Such as this is the original document: <p>Hello world!</p>

Now I want to insert an element in to the text so that it will become:

<p>Hello <span id=span1>new</span> world!</p>

I need the span tag because I want to handle it later.Show or hide. But now problem comes out, if the original page has already defined a strange CSS style on all <span> tags, the "new" I just inserted will not appear to be the same as "Hello" and "world". How can I avoid this? I want the "new" be exactly the same as the "Hello" and "world".

Upvotes: 2

Views: 1421

Answers (5)

Sev
Sev

Reputation: 15699

Include the class definition that's defined in CSS on your JavaScript version of the <span> tag as well.

<span class="class_defined_in_css">

(where this <span> tag would be part of your JavaScript code.)

Upvotes: 0

Prestaul
Prestaul

Reputation: 85137

Simply override any span styles. Set layout properties back to browser defaults and set formating to inherit from the parent:

span#yourSpan {
  /* defaults */
  position: static;
  display: inline;
  margin: 0;
  padding: 0;
  background: transparent;
  border: none;

  /* inherit from parent node */
  font: inherit;
  color: inherit;
  text-decoration: inherit;
  line-height: inherit;
  letter-spacing: inherit;
  text-transform: inherit;
  white-space: inherit;
  word-spacing: inherit;
}

This should be sufficient, although you may need to add !important if you are not using an id:

<span class="hello-node">hello</span>

span.hello-node {
  /* defaults */
  position: static !important;
  display: inline !important;
  ...
}

Upvotes: 1

Prestaul
Prestaul

Reputation: 85137

The only way to do this is to either modify the other spans to include a class name and only apply the styles to spans with that class, or override the styles set for all spans for your new span.

So if you've done:

span {
  display: block;
  margin: 10px;
  padding: 10px;
}

You could override with:

<span style="display: inline; margin: 0; padding: 0;">New Span</span>

Upvotes: 1

Jason Bunting
Jason Bunting

Reputation: 58931

Well, I don't know how married you are to using a <span> tag, but why not do this?

<p style="display: inline">Hello <p id="myIdValue" style="display: inline">new</p> World</p>

That way the inserted html retains the same styling as the outer, and you can still have a handle to it, etc. Granted, you will have to add the inline CSS style, but it would work.

Upvotes: 1

dreamlax
dreamlax

Reputation: 95315

Why not give the paragraph an id and then use Javascript to add the word, or remove it, if necessary? Surely it will retain the same formatting as the paragraph when you insert the word "new", or change the contents of the paragraph entirely.

Upvotes: 0

Related Questions