0

My issue is: I have a html string, that is also on web page.

Now I want that this html string should work as selector for jQuery.

Here is the doc html

<body>
   <p>asdf</p>
   <p>ghjk</p>
</body>

Now we have a string

 '<p><asdf</p>'

now

$('<p><asdf</p>').css("border",'1px solid red')

should read that paragraph border on document.

Any help will be appreciated!

fidlle:http://jsfiddle.net/eJxDb/2/

9
  • I think you need the contains selector: $('p:contains(asdf)').css("border",'1px solid red') Commented Mar 28, 2014 at 10:02
  • I have tried contians selector but it is not applying on rendered document. Commented Mar 28, 2014 at 10:04
  • this question does not make any sense. Commented Mar 28, 2014 at 10:12
  • Why @Jai?, I need solution and tried a lot. Commented Mar 28, 2014 at 10:13
  • i mean if the text is dynamic then why should we check for text to apply css to it. Commented Mar 28, 2014 at 10:15

2 Answers 2

1

You can use parseHTML and the html() function of JQuery :

Exemple :

http://jsfiddle.net/N6s8F/1/

JavaScript :

var obj = "<p>asdf</p>"
selector = $.parseHTML(obj)[0].nodeName;
text = $(obj).html();
console.log(text);
$(selector).each(function(index) {
console.log($(this).html());
console.log(text);
if ($(this).html() == text) {
    $(this).css('border','1px solid red');
    }
});
Sign up to request clarification or add additional context in comments.

4 Comments

can we optimize that ?
Probably, You can delete the console logs :D and you will have only 4 lines of code. After that I don't see any optimization to apply.
actually i am taking about comparing, gathering and looping.
With the information you have to retreive the element I dont see any way but it may be before like when you get the string or how it is store in the database that need to be optimize.
0

Give the paragraph id and the select it via id like this:

<p id="myID"><asdf</p>

And your jQuery:

('#myID').css("border",'1px solid red');

1 Comment

It is very dynamic , and result is not for any particular!

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.