简体   繁体   中英

changing untagged elements within the DOM

I am looking for a way to manipulate untagged elements within the DOM preferably with CSS, if not possible, than with JQuery.

In this example a JS file is populating the HTML but the person did not wrap the separator/pipes in tags.

What are my options here?

在此处输入图像描述

 function tagIt(parent, untagged, tagType, className) { var span = document.createElement(tagType); parent.insertBefore(span, untagged); span.appendChild(untagged); span.classList.add(className); } function getUntagged(element) { var children = element.childNodes; var max = children.length; var untagged = []; for (i = 0; i < max; i++) { if (children[i].nodeType === 3) { untagged.push(children[i]); } } return untagged; } // Working example: function tagify() { var container = document.querySelector('.container'); var untagged = getUntagged(container); untagged.forEach(node => { tagIt(container, node, 'span', 'tagged'); }); } document.querySelector('.tagify').addEventListener('click', tagify);
 .tagged { color: red; font-weight: bold; font-size: 2em; }
 <h2>Click the button to tag vertical bars</h2> <button class="tagify">Tag them</button> <div class="container"> <a href="#" class="placeholder">anchor</a> | <a href="#" class="placeholder">anchor</a> | <a href="#" class="placeholder">anchor</a> | </div>

To do this correctly you need to find the offending script and add your <span> tags around the | . You could also monkey patch it like this and it will work as well (BUT DONT!):

You could reuse this method I wrote you to replace any char in any element with any character or set of characters/elements/etc.

 var targetSelector = '.small'; function wrapChar(targetSelector, char, replaceWith) { 'use strict'; var content = $(targetSelector).html(); content = content.replace(new RegExp(/\|/, "g"), replaceWith); return content; } $(function() { $(targetSelector).html(wrapChar(targetSelector, ['|'], '<span class="pipe">|</span>')); });
 .pipe { font-size: 3em; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td class="small"> <a href="#">test 1</a> | <a href="#">test 2</a> | <a href="#">test 3</a> | <a href="#">test 4</a> </td> </tr> </table>

http://codepen.io/nicholasabrams/pen/PNBomg?editors=1010

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM