0

Unless I did a mistake, I didn't find a clean/simple answer to my problem.

I have a tags in a string and containing a src attribute :

var str = "<iframe src="https://www.google.com/" height="800" width="500"></iframe>"

Using JS or AngularJS (ONLY !) I want to extract somehow an attribute, for example src :

str.dosmthg("src","http://stackoverflow.com/");

Output :

"<iframe src="http://stackoverflow.com/" height="800" width="500"></iframe>"

Same idea with height and width.

Any suggestions ? Thanks !

2
  • You can simply use javascript to achieve what you want. Using jquery it can be done very easily. Have a look at below link w3schools.com/jquery Commented Jun 8, 2016 at 14:40
  • You could have separate variables in your controller if you are building it there anyways. Then just concatenate the variables as you build the element string. That way you have the height/width/etc vars later if you need them. Commented Jun 8, 2016 at 14:44

2 Answers 2

2

You should create a temp element and put your HTML into its innerHTML. Then you will be able to manipulate child nodes attributes.

var tempEl = document.createElement('div');
tempEl.innerHTML = '<iframe src="https://www.google.com/" height="800" width="500"></iframe>';
console.log(tempEl.childNodes[0].attributes['src'].value);
tempEl.childNodes[0].attributes['src'].value = 'http://stackoverflow.com';
console.log(tempEl.childNodes[0].attributes['src'].value);
console.log(tempEl.innerHTML);

Sign up to request clarification or add additional context in comments.

Comments

2

You use the browser to parse the HTML, then read the attribute values from the resulting DOM element; see comments:

// Your string
var str = '<iframe src="https://www.google.com/" height="800" width="500"></iframe>';

// Create an appropriate parent element for the string; note we don't
// actually attach this to the DOM anywhere
var body = document.createElement('body');

// Use the element to parse the HTML
body.innerHTML = str;

// Get the iframe from the element
var iframe = body.querySelector("iframe");

// Get the attributes from the element
console.log("src = ", iframe.getAttribute("src"));
console.log("height = ", iframe.getAttribute("height"));
console.log("width = ", iframe.getAttribute("width"));

Comments

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.