SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Addict
    Join Date
    Sep 2008
    0 Post(s)
    0 Thread(s)

    Non-jQuery changing HTML / the DOM

    I'm looking at a non-jQuery way to change HTML / the DOM.

    So if I have this:

    <ul class="class-name" data-value="the-value" data-abc="1">

    … and I want to change it to:

    <input type="text" class="class-name" value="the-value" />

    So, that would:
    - remove all <li> inside
    - convert to <input type="text"> (or another specified input type)
    - convert the data-value attribute to a value attribute
    - maintain any other attributes if applicable (e.g. an id)
    - remove the data-abc attribute (not all data- attributes, just a chosen one)

    … this isn't any specific need, I just want to be able to make changes without jQuery.

    I will usually always grab the required element from a data- attribute, and I have this to start me off. Can someone help me compete this so I can create all other ones myself?

    var e = document.querySelectorAll('[data-abc]');
    for (i = 0; i < e.length; i++) {

  2. #2
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    219 Post(s)
    12 Thread(s)

    Maybe a good way to go about it would be to grab any <ul> elements with a class name of "class-name"
    Harvest all of the attributes you need.
    Discard the rest.
    Create a new input element.
    Replace the <ul> element with the <input> element.

    Here is a script that does that.
    It's not complete (in so far as it doesn't do everything you request above) and could do with some optimizing, but hopefully it will point you in the right direction.

    HTML Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
    <html xmlns="">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>JavaScript DOM manipulation</title>
        <style>input {display:block;}</style>
        <ul class="class-name" data-value="the-value" data-abc="1">
        <ul class="class-name2" data-value="the-value2" data-abc="2">
        <ul class="class-name" data-value="the-value3" data-abc="3">
        <div id="newstuff"></div>
          var c = "class-name";
          var lists = document.getElementsByTagName("ul");
          for (var i = 0; i < lists.length; i++) {
            var nodes=[], values=[];
            for (var attr, j=0, attrs=lists[i].attributes, l=attrs.length; j<l; j++){
              attr = attrs.item(j)
            if (values.indexOf(c) >= 0){
              var input = document.createElement("input");
              input.type = "text";
              input.className = c;
              input.value = values[nodes.indexOf("data-value")];


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts