using JavaScript? Here's an example of what I'm trying to change:

Is it possible to edit the content of "w370" type = "text / template"> using JavaScript?

Here's an example of what I'm trying to change:

<script id="login-popup" type="text/template"> 
  <h3 id="cover-msg" class="modal-title">You need to login to do that.</h3>`
</script>

      

I would like to add: class="title"

to the h3 tag. This is done with a chrome extension, so I cannot manage the rendered HTML.

Here's a caveat: I can't assume the template will always be the same, so I can't just replace or edit the whole thing. I need to be able to select certain elements in the text and only add as needed.

The problem I am facing is that the template appears to be just text. So I can't select it with #login-popup #cover-msg

. Please correct me if I am wrong.

Can this be done with JavaScript / jQuery?

+3


source to share


1 answer


You can follow this type of procedure, which takes the text out of the script tag, inserts it into a DOM element, so you can use DOM manipulation on it, and then get the resulting HTML from that DOM element. This avoids any manual parsing of the HTML text:

var t = document.getElementById("login-popup");
var div = document.createElement("div");
div.innerHTML = t.innerHTML;
$(div).find("h3").addClass("title");
t.innerHTML = div.innerHTML;

      

This follows this process:



  • Get innerHTML from script tag
  • Create a temporary div
  • Inserts HTML into a temporary div where you can treat it like DOM elements.
  • Using DOM query find <h3>

  • Adds a class to it
  • Get HTML back from temporary div
  • Returns HTML back to the script tag as a modified version of the template.

It works here: http://jsfiddle.net/jfriend00/mqnf1mmp/ .

+5


source







All Articles