Skip to content Skip to sidebar Skip to footer

Selecting Text Only Following Certain Elements Using Javascript/jquery

As shown in the following snippet I have multiple divs of text where there is a bolded portion, then a line break then a piece of text. I can find() the bolded portion but how can

Solution 1:

i don't think there's a really easy way of getting all the nodes and seperating them etc. but it sure is possible. Since I have no idea what you intend to do with the text, i made a neat little object containing everything that should be easier to work with, or you can change the code to fit your needs:

var elem    = $('.thecontent').get(0).childNodes,
    content = {},
    i = 0;

for (key in elem) {
    vartype = elem[key].tagName ? elem[key].tagName : 'text';
    content[i] = {};
    content[i][type] = elem[key].tagName == 'B' ? $(elem[key]).text() : elem[key].nodeValue;
    i++;
}

console.log( content );

FIDDLE

This returns:

{"0": {"text" : "any amount of text or html elements before"},
 "1": {"B"    : "the bolded text"},
 "2": {"text" : "\n"}, //also returns newlines
 "3": {"BR"   : null},
 "4": {"text" : "the text I need together with the bolded text which can contain other html elements apart from line breaks and bolded blocks"},
 "5": {"BR"   : null},
 "6": {"text" : "\n"},
 "7": {"B"    : " posibility of more bolded and text couples further in the div"},
 "8": {"text" : "\n"},
 "9": {"BR"   : null},
 "10":{"text" : "and some more text to go with the bolded text"},
}

You can filter this based on line number (starting with zero), tagnames, text content, or anything else you need ?

Post a Comment for "Selecting Text Only Following Certain Elements Using Javascript/jquery"