开发者

Javascript Solution Remove Specific Tag but leave the rest in a specific DIV

I have a div structure that looks like this...

<div class="gallery_lightview">
    <div id="lg_image">
        <a href="http://www.website.com/?iframe=true&width=100%&height=100%" rel="prettyPhoto[iframes]" class="lightview_main" title="TITLE HERE">
            <img class="alignnone" src="HEADER.jpg" alt="" />
        </a>开发者_如何学Python;
    </div>
</div>

What I want to do is remove the tags that show up ONLY between div class "gallery_lightview" and leave the tag. So once its all stripped out it would look like...

<div class="gallery_lightview">
    <div id="lg_image">
        <img class="alignnone" src="HEADER.jpg" alt="" />
    </div>
</div>

Basically making this a non clickable image. Is this possible? Its going on a Mobile site and I don't want this to be in the header. Really wanted it to be a self contained Javascript that sat above the "the_content" Wordpress call (which is where the "gallery_lightview" div code is.

I choose to not use a jQuery because, since its mobile it would add to the load. And literally the only thing the library would be doing was removing the <a> tag.

Any ideas?


Could you do something like take the innerHTML of the inner element and make it the innerHTML of the grandparent. So:

var div = document.getElementById('lg_image');
var img = div.childNodes[0].childNodes[0];
div.innerHTML = img.innerHTML;

This isn't pretty, but it's lightweight and works. The more elegant option might be to pare down jQuery or find a similar, lighter-weight library.


Pure JS solution - I've given the target <a> an id of "target". You can grab the object however you wish:

HTML:

<div class="gallery_lightview">
    <div id="lg_image">
        <a href="foo" rel="bar" class="baz" title="TITLE HERE" id='target'>
          <img class="alignnone" src="HEADER.jpg" alt="" />
        </a>
    </div>
</div>

Javascript:

// Grab anchor object
var target = document.getElementById('target');
// Grab img object, using tagName to avoid possible text nodes
var img = target.getElementsByTagName("IMG");

// Append the image object as a direct child of the parent
target.parentNode.appendChild(img[0]);
// Remove the anchor (empty except for text nodes)
target.parentNode.removeChild(target);

If you wish to do this to many nodes, you can use the getElementsByTagName() to grab all <a>s, and then loop through using this process.

EDIT

The appendChild line was missing an array index [0], now added.

UPDATE

http://www.jsfiddle.net/steve/yTcxn/ is a simplified version, thoroughly commented, and tested working on FF, IE, and Chrome. It should do exactly what you want with a little personalization.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜