2

I am adding some HTML tags using JavaScript like this:

function createTag(text) {
    if (text != '') {
        text = text.replace(',', '');
        if (/^\s+$/.test(text) == false) {
            var tag = $('<div class="tags">' + text + '<a class="delete">X</a></div>');
            tag.insertBefore($('input.tag_list'), $('input.tag_list'));
            $('input.tag_list').val('');
        }
    }

I want to get the values in the <div class="tags"> tags from all over the page. How can I do it?

Also how can I restrict the number of dynamically created tags of these types?

0

1 Answer 1

1

Select the tags and use the map() function to return an array. Within the function supplied to map() remove the a from a cloned tag.

var tags = $(".tags").map(function(){
    var clone = $(this).clone();
    $(clone).find("a").remove("a");
    return clone.text();
});

JS Fiddle: http://jsfiddle.net/ELxW4/

You could make life somewhat easier by wrapping the values in span tags:

<div class="tags"><span>javascript</span><a class="delete">X</a></div>
<div class="tags"><span>java</span><a class="delete">X</a></div>
<div class="tags"><span>jquery</span><a class="delete">X</a></div>

Then get the tags using:

var tags = $(".tags").map(function(){
    return $(this).find("span").text();
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thank @kevin. But I am confused with the use of clone(). Can you explain me your JS code? As I am not so good at JS.
You need to obtain the value within the div.tags, however the div contains both a value such as javascript,java,jquery as well as an <a/>. Well I'm sure you don't want that <a/> tag included in the values. So I clone the element, which makes an exact copy, then remove the <a/> from the clone, so I can simply retrieve the value. This leaves the original element untouched, while allowing me to simply call .text() to get the value inside the div.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.