Sam
Sam

Reputation: 1

Parsing HTML in plain text or XML form

I have 2 questions:

1st Question: Can a HTML element have more than one class(be part of more than one class)?

<p class="paragraphClass" class="highlightClass"/> // is that allowed?

2nd Question: Is there a javascript HTML parser library or set of default functions that search a string of HTML & give me all the HTML elements that have a specific class? I use AJAX to get HTML from a server(returned as text not XML), I then need to convert all HTML elements that have the class "updatable" to text-area HTML elements.

What do you think would be the easiest way to convert all HTML elements of a specific class to textareas when I have a string of HTML as either text or XML.

Upvotes: 0

Views: 363

Answers (4)

Matt
Matt

Reputation: 7249

there is always jquery. You can use the selector to select all the elements with that class and then convert it to a textarea. Sounds like you want to convert it to edit that paragraph.

$(".paragraphClass").each(function{
   $(this).replaceWith("<textarea>"+ $(this).text() +"</textarea>");
})

http://jsfiddle.net/bQgN3/

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 359826

1st Question: Can a HTML element have more than one class(be part of more than one class)?

Yes, but like this:

<p class="paragraphClass highlightClass"/>

2nd Question: Is there a javascript HTML parser library or set of default functions that search a string of HTML & give me all the HTML elements that have a specific class?

The dead-simplest way to do this is with jQuery (surprise, surprise):

var html = 'your html in a string here',
    $html = $(html),
    $elts = $html.find('.someClassName');

// $elts is a (array-like) jQuery object which 
// contains all the elements in the HTML string with class 'someClassName'

See the jQuery selectors API docs for more.

Upvotes: 2

Paul
Paul

Reputation: 141829

1) Yes, but your syntax is not correct. You can specify more than one class separated by spaces like:

<p class="paragraphClass highlightClass"/>

2) You could just insert your HTML into the DOM using some elements .innerHTML property. That element could have display: none; so that it doesn't affect your page. Then you can use normal DOM methods on them like document.getElementByClassName('updatable'); Note that getElementByClassName() is not defined in IE so you have to write your own that selects by tagName and then iterates through them matching the classes, or use a framework like jQuery.

Upvotes: 0

Matthew Scharley
Matthew Scharley

Reputation: 132274

  1. You can have as many classes as you like on any element by seperating them with spaces. eg:

    <p class="paragraphClass highlightClass"></p>
    
  2. Use a library like jQuery to do this.

Upvotes: 1

Related Questions